package com.github.icloudpay.pay.core.service.payForAnother.helipay.service;

import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.icloudpay.pay.core.biz.PayChannelConfigBiz;
import com.github.icloudpay.pay.core.entity.PayChannelConfig;
import com.github.icloudpay.pay.core.inter.PayForAnotherQueryService;
import com.github.icloudpay.pay.core.util.HttpClientUtil;
import com.github.icloudpay.pay.core.util.MD5;
import com.github.icloudpay.pay.core.util.RSA;
import com.github.wxiaoqi.security.common.admin.pay.request.PayForAnotherQueryRequest;
import com.github.wxiaoqi.security.common.admin.pay.response.PayForAnotherQueryResponse;
import com.github.wxiaoqi.security.common.msg.ResponseCode;

/**
 * 合利宝代付查询
 * @author hexufeng
 *
 */
@Service("heliPayForAnotherQueryService")
public class HeliPayForAnotherQueryService implements PayForAnotherQueryService{
	
	private static final Logger logger = LoggerFactory.getLogger(HeliPayForAnotherQueryService.class);
	
	@Value("${pay_for_another.url}")
    private String url;
	@Autowired
	private PayChannelConfigBiz payChannelConfigBiz;

	@Override
	public PayForAnotherQueryResponse payForAnotherQuery(PayForAnotherQueryRequest payForAnotherQueryRequest) {
		
		logger.info("****************调用合利宝代付查询接口开始*******************");
		
		PayForAnotherQueryResponse payForAnotherQueryResponse = new PayForAnotherQueryResponse();
		PayChannelConfig payChannelConfig = new PayChannelConfig();
		payChannelConfig.setMerId(payForAnotherQueryRequest.getMerId());
		payChannelConfig.setPlatformId(payForAnotherQueryRequest.getPlatformId());
		payChannelConfig.setPayChannelNo(payForAnotherQueryRequest.getPayChannelNo());
		payChannelConfig.setPayCompanyNo(payForAnotherQueryRequest.getPayCompanyNo());
		PayChannelConfig channelConfig = payChannelConfigBiz.getPayChannelConfig(payChannelConfig);
		if(null == channelConfig){
			payForAnotherQueryResponse.setSucess(false);
			payForAnotherQueryResponse.setCode(ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getCode());
			payForAnotherQueryResponse.setMsg(ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getMessage());
			return payForAnotherQueryResponse;
		}
		
		Map<String,Object> sPara = new HashMap<String,Object>();
		sPara.put("P1_bizType","Transfer");
		sPara.put("P2_orderId",payForAnotherQueryRequest.getOutOrderNo());
		sPara.put("P3_customerNumber",channelConfig.getOutMerNo());//商户号
		
		//拼接签名串
		String signStr = getSignStr(sPara);
		String sign = "";
		try {
			PrivateKey key = RSA.getPrivateKey(channelConfig.getOutMerKey());
			sign = RSA.sign(signStr, key);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		sPara.put("sign",sign);
		logger.info("代付查询请求报文:{}",sPara);
		StringBuffer sbHtml = new StringBuffer();
		List<String> keys = new ArrayList<String>(sPara.keySet());
		
		//post方式传递
		sbHtml.append("<form id=\"transferSingleQueryForm\" name=\"transferSingleQueryForm\" action=\"").append(url).append("\" method=\"post\">");
		String name ="";
		String value ="";
		for (int i = 0; i < keys.size(); i++) {
			 name=(String) keys.get(i);
			 value=(String) sPara.get(name);
			if(value!=null && !"".equals(value)){
				sbHtml.append("<input type=\"hidden\" name=\"").append(name).append("\" value=\"" + value + "\"/>");
			}
		}
        
        //submit按钮控件请不要含有name属性
        sbHtml.append("<input type=\"submit\" value=\"确认查询\"></form>");
        String respJson = "";
        try {
			respJson = HttpClientUtil.doPost(url, sbHtml.toString(), "utf-8");
			logger.info("代付查询请求返回报文:{}",respJson);
			JSONObject jsonObject = (JSONObject) JSONObject.parse(respJson);
			String respSign = (String) jsonObject.get("sign");
			
			//返回值验签MD5
			Map<String,Object> responseMap = new HashMap<String,Object>();
			responseMap.put("rt1_bizType", (String) jsonObject.get("rt1_bizType"));
			responseMap.put("rt2_retCode", (String) jsonObject.get("rt2_retCode"));
			responseMap.put("rt4_customerNumber", (String) jsonObject.get("rt4_customerNumber"));
			responseMap.put("rt5_orderId", (String) jsonObject.get("rt5_orderId"));
			responseMap.put("rt6_serialNumber", (String) jsonObject.get("rt6_serialNumber"));
			responseMap.put("rt7_orderStatus", (String) jsonObject.get("rt7_orderStatus"));
			responseMap.put("rt8_reason", (String) jsonObject.get("rt8_reason"));
			responseMap.put("sign", (String) jsonObject.get("sign"));
			String signMD5Str = getSignStr(sPara);
			String verifySign = MD5.sign(signMD5Str, "utf-8");
			if(!verifySign.equals(respSign)){
				payForAnotherQueryResponse.setSucess(false);
				payForAnotherQueryResponse.setCode(ResponseCode.SIGN_MATCH_FAIL.getCode());
				payForAnotherQueryResponse.setMsg(ResponseCode.SIGN_MATCH_FAIL.getMessage());
			}else{
				if("0000".equals((String) jsonObject.get("rt2_retCode"))){
					payForAnotherQueryResponse.setOrderStatus((String) jsonObject.get("rt7_orderStatus"));
					payForAnotherQueryResponse.setSucess(true);
					payForAnotherQueryResponse.setCode(ResponseCode.OK.getCode());
					payForAnotherQueryResponse.setMsg(ResponseCode.OK.getMessage());
				}else{
					payForAnotherQueryResponse.setSucess(false);
					payForAnotherQueryResponse.setCode(ResponseCode.PAY_FOR_ANOTHER_FAIL.getCode());
					payForAnotherQueryResponse.setMsg(ResponseCode.PAY_FOR_ANOTHER_FAIL.getMessage());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			payForAnotherQueryResponse.setSucess(false);
			payForAnotherQueryResponse.setCode(ResponseCode.PAY_FOR_ANOTHER_FAIL.getCode());
			payForAnotherQueryResponse.setMsg(ResponseCode.PAY_FOR_ANOTHER_FAIL.getMessage());
			return payForAnotherQueryResponse;
		}
		return payForAnotherQueryResponse;
	}
	
	/**
	 * 拼接待签名字符串
	 * @param sPara
	 * @return
	 */
	private String getSignStr(Map<String,Object> sPara){
		StringBuffer sbHtml = new StringBuffer();
		List<String> keys = new ArrayList<String>(sPara.keySet());
		
		//post方式传递
		String name ="";
		String value ="";
		for (int i = 0; i < keys.size(); i++) {
			 name=(String) keys.get(i);
			 if(null != sPara.get(name)){
				 value=String.valueOf(sPara.get(name));
			 }
			if(value!=null && !"".equals(value)){
				sbHtml.append("&").append(value);
			}else{
				sbHtml.append("&");
			}
		}
		String paramStr = sbHtml.toString();
		return paramStr;
	}

}
